/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
 var minSpaceWastedKResizing = function(nums, k) {
  const n = nums.length
  if(k >= n-1){
    return 0
  }
  const max = Math.max(...nums)
  let cnt = 0 
  const map = new Map()
  let pre = nums[0]
  for(let i = 0; i<n; i++){
    if(nums[i] > pre){
      cnt++
      pre = nums[i]
      map.set(cnt, nums[i])
    }
    if(nums[i] === max){
      break
    }
  }
  let now = nums[0]
  if(cnt > k){
    now = map.get(cnt-k)
  }
  // console.log(map, now)
  let ans = 0
  for(let i =0; i<n; i++){
    if(nums[i] > now && k > 0){
      now = nums[i]
      k--
    }else if(nums[i] < now && k > 1){
      k--
      now = nums[i]
    }
    console.log(now)
    ans += now-nums[i]
  }
  return ans
};